package com.xsherl.leetcode.solution;

import com.xsherl.leetcode.base.ListNode;

/**
 * @Author: sherl
 * @Date: 2021/5/24 20:56
 */
public class ReverseLinkedList2 {

    public ListNode reverseBetween(ListNode head, int left, int right) {
        int index = 1;
        ListNode node = head, preHead = new ListNode(-1, head), tail = null;
        while (index <= right){
            ListNode t = node.next;
            if (index < left){
                // 记录翻转的左边界的上一个节点
                preHead = node;
            } else if (left == index){
                // 记录翻转列表的头
                tail = node;
            } else {
                // 采用头插法翻转列表
                tail.next = node.next;
                node.next = preHead.next;
                preHead.next = node;
            }
            node = t;
            ++index;
        }
        return left == 1 ? preHead.next : head;
    }

}
